<?php
namespace App\Libs;

use Interop\Container\ContainerInterface;

class wxhelp{
    /**
     * @var string appid
     */
    private $appid;
    /**
     * @var string $secret
     */
    private $secret;
    /**
     * @var string $secret
     */
    private $name;
    /**
     * @var ContainerInterface
     */
    private $container;
    public function __construct($appid = "",$secret="",$name = "")
    {
        $this->appid  = $appid;
        $this->secret = $secret;
        $this->name   = $name;
    }

    public function setContainer(ContainerInterface $container){
        $this->container = $container;
    }

    public function getAccesstoken(){
        $cachePath = $this->container->get("settings")['cache']['token_path'];
        if(!is_dir($cachePath)){
            mkdir($cachePath);
        }
        $tokenFile = $cachePath.$this->name."_access_token.txt";//缓存文件名
        if(file_exists($tokenFile)){
            $data = json_decode(file_get_contents($tokenFile));
        }else{
            $data =(object)["expire_time"=>"","access_token"=>""];
        }
        if ($data->expire_time < time() or !$data->expire_time) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->secret;
            $res = $this->getJson($url);
            $access_token = $res['access_token']?$res['access_token']:"";
            if($access_token){
                $result['expire_time'] = time() + 7000;
                $result['access_token'] = $access_token;
                $fp = fopen($tokenFile, "w");
                $ret = fwrite($fp, json_encode($result));
                $this->container->get("logger")->addInfo("accessToken write result".$ret);
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    public function getUserInfo($openid){
        $token = $this->getAccesstoken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid";
        $res = $this->getJson($url);
        return $res;
    }

    //取得微信返回的JSON数据 　
    private function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}